package com.ys.service.hr.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ys.config.MenuId;
import com.ys.dto.AddDto;
import com.ys.entity.business.ThrOperateCompanyBrand;
import com.ys.entity.business.ThrOperateCompanyEuropeTrade;
import com.ys.entity.business.ThrOperateCompanyVps;
import com.ys.entity.business.TpAmazonSeller;
import com.ys.entity.hr.ThrOperateCompanyBeian;
import com.ys.entity.sys.*;
import com.ys.mapper.business.ThrOperateCompanyBrandMapper;
import com.ys.mapper.business.ThrOperateCompanyEuropeTradeMapper;
import com.ys.mapper.business.ThrOperateCompanyVpsMapper;
import com.ys.mapper.business.TpAmazonSellerMapper;
import com.ys.service.business.ThrOperateCompanyEuropeTradeService;
import com.ys.util.CheckUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ys.constant.AppConstant;
import com.ys.dto.DtreeSqlDto;
import com.ys.dto.DtreeSqlDto.DataDto;
import com.ys.dto.EditDto;
import com.ys.entity.hr.ThrOperateCompanyApply;
import com.ys.enume.flow.YsProcInstEnum;
import com.ys.mapper.hr.HrMapper;
import com.ys.mapper.hr.ThrOperateCompanyApplyMapper;
import com.ys.service.hr.ThrOperateCompanyApplyService;
import com.ys.util.dh.DhPassUtil;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.R;

@Service("thrOperateCompanyApplyService")
public class ThrOperateCompanyApplyServiceImpl implements ThrOperateCompanyApplyService {
	private static final Logger logger = LoggerFactory.getLogger(ThrOperateCompanyApplyServiceImpl.class);
	@Autowired
	private HrMapper hrMapper;
	@Autowired
	private ThrOperateCompanyApplyMapper thrOperateCompanyApplyMapper;
	@Autowired
	private ThrOperateCompanyVpsMapper thrOperateCompanyVpsMapper;
	@Autowired
	private ThrOperateCompanyBrandMapper thrOperateCompanyBrandMapper;
	@Autowired
	private ThrOperateCompanyEuropeTradeMapper thrOperateCompanyEuropeTradeMapper;
	@Autowired
	private ThrOperateCompanyEuropeTradeService thrOperateCompanyEuropeTradeService;
	@Autowired
	private CheckUtil checkUtil;
	@Autowired
	private TpAmazonSellerMapper tpAmazonSellerMapper;

	@Override
	public R search(Map<String, Object> params) throws Exception {
		return null;
	}
	
	@Override
	@Transactional
	public R edit(Map<String, Object> params) throws Exception {
		logger.info("传参:"+params);
		ThrOperateCompanyApply entity = JSON.parseObject(JSON.toJSONString(params), ThrOperateCompanyApply.class);
		
		// 验证编码
		String vGsBm = entity.getVgsbm();
		if (new ThrOperateCompanyApply().setVgsbm(vGsBm).where("A.Id != '" + params.get("id").toString() + "'").count() > 0) {
			return R.error("公司编码【" + vGsBm + "】已存在");
		}

		if(checkUtil.isNotNullByObject(params.get("userId"))){
			TsUserChange tsUserChange = new TsUserChange().setUserId(params.get("userId").toString()).setStatus(1).queryFirst();
			if(tsUserChange!=null){
				entity.setOperatorChangeId(tsUserChange.getId());
			}
		}

		
		// 验证所属运营机构
		Long operateOrgId = entity.getOperateOrgId();
		if (operateOrgId == null) {
			return R.error("所属运营机构不能为空");
		}
		// 若机构有变动，验证是否是旧机构主管
		ThrOperateCompanyApply entityOld = new ThrOperateCompanyApply().setId(entity.getId()).queryFirst();
		Long operateOrgIdOld = entityOld.getOperateOrgId();
		if (operateOrgIdOld != null && operateOrgIdOld.longValue() != operateOrgId.longValue()) {
			if (new TsOperateOrg().setHeadVgsbm(vGsBm).setId(operateOrgIdOld).count() > 0) {
				return R.error("该运营公司为机构主管，无法变更所属机构");
			}
		}

		//公司停用同步停用|停用店铺卖家
		if(entity.getOperationsStatus()!=null){
			if (entity.getOperationsStatus() == 4 || entity.getOperationsStatus() == 2){
				Integer status = 0;
				if (entity.getOperationsStatus() == 4){
					status = 0;
				}else {
					status = 1;
				}
				List<TpAmazonSeller> tpAmazonSellerList = new TpAmazonSeller().setVgsbm(entity.getVgsbm()).queryList();
				for (TpAmazonSeller tpAmazonSeller :tpAmazonSellerList){
					tpAmazonSeller.setStatus(status);
					tpAmazonSellerMapper.update(tpAmazonSeller);
				}
			}
		}
		
		thrOperateCompanyApplyMapper.update(entity);
		return R.ok("操作成功");
	}


	@Override
	@Transactional
	public void repairNode(String vGsBm) throws Exception {
		System.out.println("vGsBm---" + vGsBm);
		ThrOperateCompanyApply entity = new ThrOperateCompanyApply().setVgsbm(vGsBm).queryFirst();

		thrOperateCompanyApplyMapper.update(entity);
	}

	@Override
	@Transactional
	public DtreeSqlDto dtree() {
		
		DtreeSqlDto.StatusDto status = DtreeSqlDto.StatusDto.init(200, "");

		List<DtreeSqlDto.DataDto> data = new ArrayList<DtreeSqlDto.DataDto>();
		
		List<TsOperateOrg> listThrOperateCompanyApply = new TsOperateOrg()
				.setOrderby("A.Floor asc,A.Id asc")
				.queryList();
		Map<Long, List<TsOperateOrg>> MAP_PID_ENTITY = new HashMap<Long, List<TsOperateOrg>>();
		for(TsOperateOrg entity : listThrOperateCompanyApply) {
			Long pid = entity.getPid();
			List<TsOperateOrg> list = MAP_PID_ENTITY.containsKey(pid) ? MAP_PID_ENTITY.get(pid) : new ArrayList<TsOperateOrg>();
			list.add(entity);
			MAP_PID_ENTITY.put(pid, list);
		}
		
		// 顶级菜单
		for(TsOperateOrg root : MAP_PID_ENTITY.get(0L)) {
			String id1 = root.getId().toString();
			String title1 = root.getName();
			String parentId1 = root.getPid().toString();
			
			// 子菜单
			List<DtreeSqlDto.DataDto> children = getChildrens(root.getId(), MAP_PID_ENTITY);
			
			DtreeSqlDto.DataDto dataDto1 = new DtreeSqlDto.DataDto(id1, title1, parentId1, DtreeSqlDto.DataDto.initCheckArr(null), children);
			data.add(dataDto1);
		}
		return new DtreeSqlDto(status, data);
	}

	@Override
	public List<DataDto> getChildrens(Long pid, Map<Long, List<TsOperateOrg>> map) {
		List<DtreeSqlDto.DataDto> children = new ArrayList<DtreeSqlDto.DataDto>();
		List<TsOperateOrg> list = map.get(pid);
		if (list == null || list.size() == 0) {
			return children;
		} else {
			for (TsOperateOrg sub : list) {
				String id2 = sub.getId().toString();
				String title2 = sub.getName();
				String parentId2 = sub.getPid().toString();

				// 三级菜单
				List<DtreeSqlDto.DataDto> children1 = getChildrens(sub.getId(), map);

				DtreeSqlDto.DataDto dataDto2 = new DtreeSqlDto.DataDto(id2, title2, parentId2, DtreeSqlDto.DataDto.initCheckArr(null), children1);
				children.add(dataDto2);
			}
		}
			return children;

	}

	@Override
	public R editOperator(Long id, String cUser, String password) throws Exception {
		
		// 验证登录密码
		String loginUserId = ShiroUtils.getUserId();
		TsUserInfo tsUserInfo = new TsUserInfo().setUserId(loginUserId).queryFirst();
		String passEncrypt = DhPassUtil.encryptPassword(loginUserId, password, AppConstant.PASSWORD_SALT);
		if (!passEncrypt.equals(tsUserInfo.getUserPassWord())) {
			return R.error("密码不正确");
		}
		
		// 验证新工号
		TsUserInfo tsUserInfoNew = new TsUserInfo().setUserId(cUser).queryFirst();
		if (tsUserInfoNew == null) {
			return R.error("工号有误");
		}
		ThrOperateCompanyApply entity = new ThrOperateCompanyApply().setId(id).queryFirst();
		entity.setCuser(cUser);
			//.setCUserName(tsUserInfoNew.getUserName());
		thrOperateCompanyApplyMapper.update(entity);


		return R.ok();
	}

	@Override
	public R editStatus(Long id, Integer status, String password) throws Exception {
		
		// 验证登录密码
		String loginUserId = ShiroUtils.getUserId();
		TsUserInfo tsUserInfo = new TsUserInfo().setUserId(loginUserId).queryFirst();
		String passEncrypt = DhPassUtil.encryptPassword(loginUserId, password, AppConstant.PASSWORD_SALT);
		if (!passEncrypt.equals(tsUserInfo.getUserPassWord())) {
			return R.error("密码不正确");
		}
		ThrOperateCompanyApply entity = new ThrOperateCompanyApply().setId(id).queryFirst();
		entity.setStatus(status);
		thrOperateCompanyApplyMapper.update(entity);
		
		
		return R.ok();
	}

	@Override
	@Transactional
	public R editSupper(Long id, String vGsBmP, String password) throws Exception {
		
		// 验证登录密码
		String loginUserId = ShiroUtils.getUserId();
		TsUserInfo tsUserInfo = new TsUserInfo().setUserId(loginUserId).queryFirst();
		String passEncrypt = DhPassUtil.encryptPassword(loginUserId, password, AppConstant.PASSWORD_SALT);
		if (!passEncrypt.equals(tsUserInfo.getUserPassWord())) {
			return R.error("密码不正确");
		}

		// 验证不在同个分支下
		ThrOperateCompanyApply entity = new ThrOperateCompanyApply().setId(id).queryFirst();

		thrOperateCompanyApplyMapper.update(entity);
		
		return R.ok();
	}

	@Override
	public R batchChangeOrg(Long operateOrgId, String detailArr) {
		
		if (operateOrgId == null) {
			return R.error("运营机构ID不能为空");
		}
		
		//  组织机构是否已有主管
		TsOperateOrg org = new TsOperateOrg().setId(operateOrgId).queryFirst();
		if (org.getHeadVgsbm() == null || org.getHeadVgsbm().length() == 0) {
			return R.error("所选运营机构尚未设置主管公司");
		}
		
		// 验证是否是机构主管
		JSONArray detailJA = JSON.parseArray(detailArr);
		for (int i = 0; i < detailJA.size(); i++) {
			JSONObject detailJO = detailJA.getJSONObject(i);
			String vgsbm = detailJO.getString("vgsbm");
			if(new TsOperateOrg().setHeadVgsbm(vgsbm).count() > 0) {
				return R.error("编号【" + vgsbm + "】为机构主管，无法变更");
			}
		}
		for (int i = 0; i < detailJA.size(); i++) {
			JSONObject detailJO = detailJA.getJSONObject(i);
			Long id = detailJO.getLong("id");
			
			ThrOperateCompanyApply tsUserInfo = new ThrOperateCompanyApply()
					.setId(id)
					.setOperateOrgId(operateOrgId);
			thrOperateCompanyApplyMapper.update(tsUserInfo);
		}
		return R.ok(EditDto.closeAndReload());
	}

	@Override
	@Transactional
	public ThrOperateCompanyApply add(Map<String, Object> params) throws Exception {
		ThrOperateCompanyApply entity = JSON.parseObject(JSON.toJSONString(params), ThrOperateCompanyApply.class);
		entity.setStatus(1);
		thrOperateCompanyApplyMapper.insert(entity);
		return entity;
	}



	/**
	 * 运营公司档案页面修改
	 */
	@Override
	@Transactional
	public R editByArchives(Map<String, Object> params,Long menuId, boolean hasSonList) throws Exception {
		logger.info("运营公司档案保存传参："+params);

		//参数验证
		String errorMsg = checkParams(params,menuId);
		if(errorMsg!=null && !"".equals(errorMsg)){
			return R.error(errorMsg);
		}
		//去除多余参数，只保留有权限编辑的参数
		Map<String, Object> paramsNew = removeSurplusParams(params,menuId,hasSonList);

		ThrOperateCompanyApply entity = JSON.parseObject(JSON.toJSONString(paramsNew), ThrOperateCompanyApply.class);
		if(params.get("operatorUserId")!=null && !"".equals(params.get("operatorUserId"))){
			//根据运营人工号获取运营人变更id
			TsUserChange tsUserChange = new TsUserChange().setUserId(params.get("operatorUserId").toString()).setOrderby("A.Id DESC").queryFirst();
			if(tsUserChange!=null){
				entity.setOperatorChangeId(tsUserChange.getId());
				entity.setCuser(tsUserChange.getUserId());
			}else{
				return R.error( "运营人工号信息有误！");
			}
		}

		if(entity.getOperationsStatus()!=null){
			try {
				Map<String, Object> paramsByCompanyApply = new HashMap<>();
				if(entity.getOperationsStatus()==4){
					paramsByCompanyApply.put("deleted",1);
				}else{
					paramsByCompanyApply.put("deleted",0);
				}
				paramsByCompanyApply.put("effectStock",1);
				paramsByCompanyApply.put("id",entity.getId());
				hrMapper.updateThrOperateCompanyApplyByOld(paramsByCompanyApply);
			}catch (Exception e){
				logger.info("表字段被删除");
			}
		}

		entity.setStatus(1);
		//公司停用同步停用|停用店铺卖家
		if (entity.getOperationsStatus() == 4 || entity.getOperationsStatus() == 2){
			Integer status = 0;
			if (entity.getOperationsStatus() == 4){
				status = 0;
			}else {
				status = 1;
			}
			List<TpAmazonSeller> tpAmazonSellerList = new TpAmazonSeller().setVgsbm(entity.getVgsbm()).queryList();
			for (TpAmazonSeller tpAmazonSeller :tpAmazonSellerList){
				tpAmazonSeller.setStatus(status);
				tpAmazonSellerMapper.update(tpAmazonSeller);
			}
		}
		thrOperateCompanyApplyMapper.update(entity);

		//保存列表信息
		if(hasSonList){
			JSONObject jsonObject = JSONObject.parseObject(params.get("subData").toString());//获取列表信息
			String vpsListStr = jsonObject.getString("vpsList");//运营公司表VPS信息
			String brandListStr = jsonObject.getString("brandList");//运营公司表品牌信息
			String europeTradeListStr = jsonObject.getString("europeTradeList");//运营公司表欧洲贸易合规

			//保存，运营公司表VPS信息
			if(vpsListStr!=null && !"".equals(vpsListStr)){
				JSONArray arrayInfo = JSON.parseArray(vpsListStr);
				if(arrayInfo!=null && arrayInfo.size()>0){
					logger.info("运营公司表VPS信息："+arrayInfo);
					for(int i=0;i<arrayInfo.size();i++){
						ThrOperateCompanyVps thrOperateCompanyVps = JSON.parseObject(JSON.toJSONString(arrayInfo.get(i)), ThrOperateCompanyVps.class);
						thrOperateCompanyVps.setStatus(1);
						thrOperateCompanyVps.setVgsbm(entity.getVgsbm());
						if(thrOperateCompanyVps.getId()!=null){
							thrOperateCompanyVpsMapper.update(thrOperateCompanyVps);
						}else {
							thrOperateCompanyVpsMapper.insert(thrOperateCompanyVps);
						}
					}
				}
			}

			//保存，运营公司表品牌信息
			if(brandListStr!=null && !"".equals(brandListStr)){
				JSONArray arrayInfo = JSON.parseArray(brandListStr);
				if(arrayInfo!=null && arrayInfo.size()>0){
					logger.info("运营公司表品牌信息："+arrayInfo);
					for(int i=0;i<arrayInfo.size();i++){
						ThrOperateCompanyBrand thrOperateCompanyBrand = JSON.parseObject(JSON.toJSONString(arrayInfo.get(i)), ThrOperateCompanyBrand.class);
						thrOperateCompanyBrand.setStatus(1);
						thrOperateCompanyBrand.setVgsbm(entity.getVgsbm());
						if(thrOperateCompanyBrand.getId()!=null){
							thrOperateCompanyBrandMapper.update(thrOperateCompanyBrand);
						}else {
							thrOperateCompanyBrand.setOtherFile("0个附件");
							thrOperateCompanyBrandMapper.insert(thrOperateCompanyBrand);
						}

					}
				}
			}

			//保存，运营公司表欧洲贸易合规
			if(europeTradeListStr!=null && !"".equals(europeTradeListStr)){
				JSONArray arrayInfo = JSON.parseArray(europeTradeListStr);
				if(arrayInfo!=null && arrayInfo.size()>0){
					logger.info("运营公司表欧洲贸易合规信息："+arrayInfo);
					for(int i=0;i<arrayInfo.size();i++){
						ThrOperateCompanyEuropeTrade thrOperateCompanyEuropeTrade = JSON.parseObject(JSON.toJSONString(arrayInfo.get(i)), ThrOperateCompanyEuropeTrade.class);
						thrOperateCompanyEuropeTrade.setStatus(1);
						thrOperateCompanyEuropeTrade.setVgsbm(entity.getVgsbm());
						thrOperateCompanyEuropeTrade = thrOperateCompanyEuropeTradeService.countVatDeclareEnd(thrOperateCompanyEuropeTrade);
						if(thrOperateCompanyEuropeTrade.getId()!=null){
							thrOperateCompanyEuropeTradeMapper.update(thrOperateCompanyEuropeTrade);
						}else {
							thrOperateCompanyEuropeTrade.setOtherFile("0个附件");
							thrOperateCompanyEuropeTradeMapper.insert(thrOperateCompanyEuropeTrade);
						}
					}
				}
			}

		}
		String editType = "detail";
		if(menuId.equals(MenuId.THR_OperateCompanyApply_By_Archives_Operations)){//运营
			editType = "operations";
		}else if(menuId.equals(MenuId.THR_OperateCompanyApply_By_Archives_Markets)){//市场
			editType = "markets";
		}else if(menuId.equals(MenuId.THR_OperateCompanyApply_By_Archives_Manage)){//管理
			editType = "manage";
		}
		//return R.ok();
		return R.ok(AddDto.gotoEdit("/web/hr/thrOperateCompanyApply/toEdit?id=" + entity.getId()+"&editType="+editType));
	}


	/**
	 * 参数验证
	 */
	public String checkParams(Map<String, Object> params,Long menuId) throws Exception {
		//获取pc字段数据
		List<YsCol> listField = new YsCol()
				.where("A.MenuId = "+menuId)
				.setOrderby("A.SortNo ASC")
				.queryList();
		//验证必填字段的非空；其他字段的长度限制、类型
		String backMsg = checkUtil.checkTableColLengthAndDataType("THR_OperateCompanyApply",listField,params,ysColItem->ysColItem.getFormEditRequired()!=null && ysColItem.getFormEditRequired() == 1);
		if(checkUtil.isNotNullByObject(params.get("corporationPhone")) && !checkUtil.isPhone(params.get("corporationPhone").toString())){
			backMsg = "法人联系方式手机号格式有误！";
		}
		if(checkUtil.isNotNullByObject(params.get("vgsFrId")) && !checkUtil.isIDNumberValid(params.get("vgsFrId").toString())){
			backMsg = "法人身份证号格式有误！";
		}
		if(checkUtil.isNotNullByObject(params.get("costtelephone")) && !checkUtil.isPhone(params.get("costtelephone").toString())){
			backMsg = "法人电话号码格式有误！";
		}
		//验证运营公司简称是否重复
		if(params.get("vgsjc")!=null){
			int isSame = new ThrOperateCompanyBeian()
					.setCode(params.get("vgsjc").toString())
					.where("A.Code != '"+params.get("vgsbm")+"'")
					.count();
			if(isSame>0){
				backMsg = "运营公司简称重复！";
			}
		}
		return backMsg;
	}


	/**
	 * 去除多余参数，只保留有权限编辑的参数
	 */
	public Map<String, Object> removeSurplusParams(Map<String, Object> params,Long menuId,boolean hasSonList) throws Exception {
		Map<String, Object> paramsNew = new HashMap<>();
		//获取pc编辑只读字段数据
		List<YsCol> listField = new YsCol()
				.where("A.MenuId = "+menuId)
				.setFormEditState(1)//是否编辑
				.queryList();
		paramsNew.put("id",params.get("id"));//id必需
		paramsNew.put("vgsbm",params.get("vgsbm"));//运营公司编码必须
		if(hasSonList){//如果有权限修改子表信息，则保留
			paramsNew.put("subData",params.get("subData"));
		}
		if(listField!=null && listField.size()>0){
			for (String key : params.keySet()) {
				boolean isReadOnly = false;//是否只读
				for (YsCol item : listField) {
					if(item.getCode().equals(key)  && item.getFormEditReadonly()!=null && item.getFormEditReadonly()==1){
						isReadOnly = true;
					}
				}
				if(!isReadOnly){//如果非只读，即是有权限修改的
					paramsNew.put(key,params.get(key));
				}
			}
		}
		return paramsNew;
	}

}
